import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:flutter_learn_vi/src/page/mine/new/wangpo/rank_time_type.dart';
import 'package:flutter_learn_vi/src/utils/log_util.dart';

import '../../../../bean/bean_integral.dart';
import '../../../../bean/bean_user.dart';
import '../../../../common/user_helper.dart';
import '../../../../net/dio_utils.dart';
import '../../../../utils/date_utils.dart';
import '../../../../utils/toast_utils.dart';
import '../../../common/common_loading_dialog.dart';
import '../../../common/common_nodata_widget.dart';

class IntegralStatTabSectorPage extends StatefulWidget {
  final String tabType;

  IntegralStatTabSectorPage({Key key, @required this.tabType})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _IntegralStatTabPageState();
  }
}

class _IntegralStatTabPageState extends State<IntegralStatTabSectorPage>
    with SingleTickerProviderStateMixin {
  bool _isLoading = true;
  bool _isLoading2 = false;

  double _pre = 0;

  @override
  void initState() {
    super.initState();
    Future.delayed(Duration.zero, () {
      getTopTabFunction();
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  String _startTime;
  String _endTime;

  buildEndDrawer() {
    return Container(
      child: ClipRRect(
        borderRadius: BorderRadius.all(Radius.circular(8)),
        child: Container(
          padding: EdgeInsets.only(left: 20, right: 20, bottom: 20, top: 20),
          width: 300,
          height: 260,
          color: Colors.white,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Text(
                    "筛选条件",
                    style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
                  )
                ],
              ),
              SizedBox(
                height: 8,
              ),
              TextButton(
                onPressed: () {
                  _selectDate(1);
                },
                child:
                    Text(_startTime == null ? "点击选择开始时间" : "开始时间 $_startTime"),
              ),
              SizedBox(
                height: 8,
              ),
              TextButton(
                onPressed: () {
                  _selectDate(2);
                },
                child: Text(_endTime == null ? "点击选择结束时间" : "结束时间 $_endTime"),
              ),
              SizedBox(
                height: 28,
              ),
              Row(
                children: [
                  GestureDetector(
                    onTap: () {
                      if (_startTime == null || _endTime == null) {
                        ToastUtils.showToast("请选择时间段");
                        return false;
                      }
                      Navigator.pop(context);
                      setState(() {
                        _isLoading2 = true;
                      });
                      getMyScoreDataFunction();
                    },
                    child: ClipRRect(
                      child: Container(
                        padding: EdgeInsets.only(
                            left: 12, right: 12, top: 8, bottom: 8),
                        color: Colors.red[900],
                        child: Text(
                          "确定",
                          style: TextStyle(
                              fontSize: 12,
                              color: Colors.white,
                              fontWeight: FontWeight.w600),
                        ),
                      ),
                      borderRadius: BorderRadius.all(Radius.circular(4)),
                    ),
                  )
                ],
                mainAxisAlignment: MainAxisAlignment.end,
              )
            ],
          ),
        ),
      ),
    );
  }

  Future<void> _selectDate(int i) async {
    final DateTime date = await DatePicker.showDatePicker(context,
        // 是否展示顶部操作按钮
        showTitleActions: true,
        // 最小时间
        minTime: DateTime(2020, 1, 1),
        // 最大时间
        maxTime: DateTime(2099, 6, 7),
        // change事件
        onChanged: (date) {
      print('change $date');
    },
        // 确定事件
        onConfirm: (date) {
      print('confirm $date');
    },
        // 当前时间
        currentTime: DateTime.now(),
        // 语言
        locale: LocaleType.zh);

    if (date == null) {
      ToastUtils.showToast("日期格式不正常 请重新选择");
      if (i == 1) {
        _startTime = null;
      } else {
        _endTime = null;
      }
      setState(() {});
      return;
    }

    String dateStr = ViDateUtils.formatDate(date, format: "yyyy-MM-dd");
    if (i == 1) {
      _startTime = dateStr;
    } else {
      _endTime = dateStr;
    }
    setState(() {});
  }

  TabController _tabController;
  List<Tab> _tabWidgetList = [];

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return LoadingWidget();
    }
    if (_tabList.length == 0) {
      return NoDataWidget(
        clickCallBack: () {
          setState(() {
            _isLoading = true;
            getTopTabFunction();
          });
        },
      );
    }

    if (_tabController == null) {
      _tabController = new TabController(length: _tabList.length, vsync: this);
      _tabList.forEach((element) {
        _tabWidgetList.add(Tab(
          text: element.name,
        ));
      });
    }
    return Scaffold(
      endDrawer: buildEndDrawer(),
      body: RefreshIndicator(
          notificationPredicate: (ScrollNotification notifation) {
            //该属性包含当前ViewPort及滚动位置等信息
            ScrollMetrics scrollMetrics = notifation.metrics;
            if (scrollMetrics.minScrollExtent == 0) {
              return true;
            } else {
              return false;
            }
          },
          onRefresh: () async {
            setState(() {
              _isLoading2 = true;
            });
            await getMyScoreDataFunction();
            ToastUtils.showToast("已刷新");
            return true;
          },
          child: SizedBox(
            width: double.infinity,
            height: double.infinity,
            child: Stack(
              children: [
                Positioned.fill(
                  top: 44,
                  child: NestedScrollView(
                    body: buildAnimatedSwitcher(context),
                    headerSliverBuilder:
                        (BuildContext context, bool innerBoxIsScrolled) {
                      return [
                        SliverToBoxAdapter(
                          child: buildAvgScoreWidget(),
                        ),
                      ];
                    },
                  ),
                ),
                Positioned(
                  top: 60,
                  left: 22,
                  child: Container(
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        InkWell(
                          onTap: () {
                            _count++;
                            _rankType = RankTimeType.yesterday;
                            setState(() {
                              _isLoading2 = true;
                            });
                            getMyScoreDataFunction();
                          },
                          child: Container(
                            alignment: Alignment.center,
                            padding: EdgeInsets.only(
                                left: 8, right: 8, top: 4, bottom: 4),
                            child: Text(
                              "昨日",
                              style: TextStyle(
                                color: _rankType == RankTimeType.yesterday
                                    ? Colors.white
                                    : Colors.red,
                              ),
                            ),
                            decoration: BoxDecoration(
                              color: _rankType == RankTimeType.yesterday
                                  ? Colors.red
                                  : Colors.white,
                              border: Border.all(color: Colors.red),
                              borderRadius: BorderRadius.only(
                                topLeft: Radius.circular(20),
                                bottomLeft: Radius.circular(20),
                              ),
                            ),
                          ),
                        ),
                        InkWell(
                          onTap: () {
                            _count++;
                            _rankType = RankTimeType.thisWeek;
                            setState(() {
                              _isLoading2 = true;
                            });
                            getMyScoreDataFunction();
                          },
                          child: Container(
                            alignment: Alignment.center,
                            padding: EdgeInsets.only(
                                left: 8, right: 8, top: 4, bottom: 4),
                            child: Text(
                              "本周",
                              style: TextStyle(
                                color: _rankType == RankTimeType.thisWeek
                                    ? Colors.white
                                    : Colors.red,
                              ),
                            ),
                            decoration: BoxDecoration(
                              color: _rankType == RankTimeType.thisWeek
                                  ? Colors.red
                                  : Colors.white,
                              border: Border.symmetric(
                                  horizontal: BorderSide(color: Colors.red)),
                            ),
                          ),
                        ),
                        InkWell(
                          onTap: () {
                            _count++;
                            _rankType = RankTimeType.thisMonth;
                            setState(() {
                              _isLoading2 = true;
                            });
                            getMyScoreDataFunction();
                          },
                          child: Container(
                            alignment: Alignment.center,
                            padding: EdgeInsets.only(
                                left: 8, right: 8, top: 4, bottom: 4),
                            child: Text(
                              "本月",
                              style: TextStyle(
                                color: _rankType == RankTimeType.thisMonth
                                    ? Colors.white
                                    : Colors.red,
                              ),
                            ),
                            decoration: BoxDecoration(
                              color: _rankType == RankTimeType.thisMonth
                                  ? Colors.red
                                  : Colors.white,
                              border: Border.all(color: Colors.red),
                              borderRadius: BorderRadius.only(
                                topRight: Radius.circular(20),
                                bottomRight: Radius.circular(20),
                              ),
                            ),
                          ),
                        ),
                        // Builder(
                        //   builder: (BuildContext context) {
                        //     return InkWell(
                        //       onTap: () {
                        //         _count++;
                        //         _rankType = RankTimeType.customDay;
                        //         Scaffold.of(context).openEndDrawer();
                        //         setState(() {});
                        //       },
                        //       child: Container(
                        //         alignment: Alignment.center,
                        //         padding: EdgeInsets.only(
                        //             left: 8, right: 8, top: 4, bottom: 4),
                        //         child: Text(
                        //           "自定义时间",
                        //           style: TextStyle(
                        //             color: _rankType == RankTimeType.customDay
                        //                 ? Colors.white
                        //                 : Colors.red,
                        //           ),
                        //         ),
                        //         decoration: BoxDecoration(
                        //           color: _rankType == RankTimeType.customDay
                        //               ? Colors.red
                        //               : Colors.white,
                        //           border: Border.all(color: Colors.red),
                        //           borderRadius: BorderRadius.only(
                        //             topRight: Radius.circular(20),
                        //             bottomRight: Radius.circular(20),
                        //           ),
                        //         ),
                        //       ),
                        //     );
                        //   },
                        // ),
                      ],
                    ),
                  ),
                ),
                Positioned(
                  top: 2,
                  left: 0,
                  right: 0,
                  child: Container(
                    color: Colors.white,
                    child: TabBar(
                      onTap: (index) {
                        _count++;
                        _rankType = RankTimeType.yesterday;
                        setState(() {
                          _isLoading2 = true;
                        });
                        getMyScoreDataFunction();
                      },
                      indicatorColor: Colors.red,
                      controller: _tabController,
                      tabs: _tabWidgetList,
                    ),
                  ),
                )
              ],
            ),
          )),
    );
  }

  ///AnimatedSwitcher 的基本使用
  AnimatedSwitcher buildAnimatedSwitcher(BuildContext context) {
    return AnimatedSwitcher(
      //动画执行切换时间
      duration: const Duration(milliseconds: 200),
      //动画构建器 构建指定动画类型
      transitionBuilder: (Widget child, Animation<double> animation) {
        //执行缩放动画
        return FadeTransition(child: child, opacity: animation);
      },
      //执行动画的子 Widget
      //只有子 Widget 被切换时才会触发动画
      child: buildItemListWidget(),
    );
  }

  buildItemListWidget() {
    if (_isLoading || _isLoading2) {
      return LoadingWidget();
    }
    if (_integralList.length == 0) {
      return NoDataWidget(
        clickCallBack: () async {
          setState(() {
            _isLoading = true;
          });
          await getMyScoreDataFunction();
          ToastUtils.showToast("已刷新");
        },
      );
    }
    return ListView.builder(
      key: ValueKey("$_count"),
      itemCount: _integralList.length,
      itemBuilder: (BuildContext context, int index) {
        IntegralStatBean item = _integralList[index];
        return Container(
          margin: EdgeInsets.only(left: 12, right: 12),
          color: Colors.white,
          child: buildItemRankContainer(item, index, _integralList.length - 1),
        );
      },
    );
  }

  Container buildItemRankContainer(
      IntegralStatBean item, int index, int lastIndex) {
    return Container(
      margin: EdgeInsets.only(top: 10, left: 1, right: 1),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(
            children: [
              SizedBox(
                width: 12,
              ),
              Container(
                child: buildItemIndex(index),
                width: 40,
                alignment: Alignment.center,
              ),
              SizedBox(
                width: 12,
              ),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      "${item.userRealName}",
                      style: TextStyle(
                        color: Colors.blueGrey,
                        fontSize: 16,
                      ),
                    ),
                    SizedBox(
                      height: 4,
                    ),
                    Text(
                      "${item.userDepartment}",
                      style: TextStyle(
                        color: Colors.grey,
                        fontSize: 14,
                      ),
                    )
                  ],
                ),
              ),
              SizedBox(
                width: 12,
              ),
              Container(
                width: 80,
                alignment: Alignment.centerRight,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    // Text(
                    //   item == null ? "无" : "${item.examineCount}次",
                    //   style: TextStyle(
                    //     color: Colors.red,
                    //     fontSize: 16,
                    //   ),
                    // ),
                    // SizedBox(
                    //   height: 4,
                    // ),
                    Text(
                      item == null ? "无" : "${item.examineScore / 100}分",
                      style: TextStyle(
                        color: Colors.grey,
                        fontSize: 14,
                      ),
                    )
                  ],
                ),
              ),
              SizedBox(
                width: 12,
              ),
            ],
          ),
          Container(
            height: 1.0,
            color: Colors.grey[200],
            margin: EdgeInsets.only(top: 8),
          ),
          index > 20 && index == lastIndex
              ? Padding(
                  padding: EdgeInsets.only(top: 20, bottom: 20),
                  child: Text("已滑动到底部"))
              : SizedBox()
        ],
      ),
    );
  }

  Widget buildItemIndex(int index) {
    return index < 3
        ? Image.asset(
            "assets/images/2.0x/icon_rank_${index + 1}.png",
            width: 26,
          )
        : Text(
            "${index + 1}",
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
          );
  }

  int _count = 0;
  RankTimeType _rankType = RankTimeType.yesterday;

//平均分
  Widget buildAvgScoreWidget() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          margin: EdgeInsets.only(top: 16, bottom: 16),
          height: 200,
          child: Stack(
            alignment: Alignment.center,
            children: [
              Positioned(
                top: 0,
                left: 0,
                right: 0,
                child: Container(
                  alignment: Alignment.center,
                  child: Image.asset(
                    buildRankImagePath(),
                    height: 200,
                  ),
                ),
              ),
              Positioned(
                top: 166,
                child: Text(
                  buildRankText(),
                  style: TextStyle(
                      color: Colors.white,
                      fontWeight: FontWeight.w600,
                      fontSize: 16),
                ),
              ),
            ],
          ),
        ),
        buildUserRankContainer()
      ],
    );
  }

  Widget buildUserRankContainer() {
    if (_userIntegralStatBean == null) {
      return Container();
    }
    UserBean userBean = UserHelper.getInstance.userBean;
    if (_isLoading2) {
      return Container();
    }
    return Container(
      height: 80,
      margin: EdgeInsets.only(top: 10, left: 12, right: 12),
      child: Stack(
        children: [
          Positioned.fill(
            child: Image.asset(
              "assets/images/2.0x/bg_ranking_list_own.png",
              fit: BoxFit.fill,
            ),
          ),
          Positioned.fill(
            child: Row(
              children: [
                SizedBox(
                  width: 12,
                ),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        "当前排行共${_integralList.length}人",
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                        ),
                      ),
                      SizedBox(
                        height: 4,
                      ),
                      Text(
                        "自己排列 第 ${_userIntegralStatBean.rankNumber} 名",
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 14,
                        ),
                      )
                    ],
                  ),
                ),
                SizedBox(
                  width: 12,
                ),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      _userIntegralStatBean == null ? "无" : "",
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 16,
                      ),
                    ),
                    SizedBox(
                      height: 4,
                    ),
                    Text(
                      _userIntegralStatBean == null
                          ? "无"
                          : "${_userIntegralStatBean.examineScore / 100}分",
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 14,
                      ),
                    )
                  ],
                ),
                SizedBox(
                  width: 12,
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

  String buildRankText() {
    if (_userIntegralStatBean == null) {
      return "暂无排名";
    } else {
      String str = "第${_userIntegralStatBean.rankNumber}名";
      return str;
    }
  }

  String buildRankImagePath() {
    if (_userIntegralStatBean == null) {
      LogUtils.e("个人排行 ");
      return "assets/images/2.0x/rank4.png";
    } else {
      String str =
          "assets/images/2.0x/rank${_userIntegralStatBean.rankNumber}.png";
      if (_userIntegralStatBean.rankNumber > 4) {
        str = "assets/images/2.0x/rank4.png";
      }
      return str;
    }
  }

  CancelToken _cancelToken;
  List<IntegralStatBean> _integralList = [];
  List<IntegralTabBean> _tabList = [];
  IntegralStatBean _userIntegralStatBean;

  Future<bool> getTopTabFunction() async {
    ResponseInfo statisRresponseInfo = await DioUtils.instance.getRequest(
      url: HttpHelper.sectorList,
      cancelTag: _cancelToken,
    );

    _isLoading = false;
    if (statisRresponseInfo.success) {
      var responseData = statisRresponseInfo.data;
      if (responseData != null && responseData["list"] != null) {
        List<IntegralTabBean> newList = [];
        for (int i = 0; i < responseData["list"].length; i++) {
          var item = responseData["list"][i];
          IntegralTabBean _rankStatBean = IntegralTabBean.fromJson(item);
          newList.add(_rankStatBean);
        }
        _tabList = newList;
      }
    }
    if (mounted) {
      setState(() {});
    }
    return true;
  }

  Future<bool> getMyScoreDataFunction() async {
    if (_isLoading2) {
      await Future.delayed(Duration(milliseconds: 400));
    }

    String _type;
    switch (_rankType) {
      case RankTimeType.yesterday:
        _type = "yesterday";
        break;
      case RankTimeType.thisWeek:
        _type = "thisWeek";
        break;
      case RankTimeType.thisMonth:
        _type = "thisMonth";
        break;
      case RankTimeType.customDay:
        _type = "customDay";
        if (_startTime == null || _endTime == null) {
          ToastUtils.showToast("请选择时间段");
          return false;
        }
        break;
    }

    IntegralTabBean select = _tabList[_tabController.index];
    Map<String, dynamic> monthMap = {
      "sort": _type,
      "tabType": widget.tabType,
      "sectorId": select.id,
    };
    if (_startTime != null) {
      monthMap["startTime"] = _startTime;
      monthMap["endTime"] = _endTime;
    }
    if (_cancelToken != null && !_cancelToken.isCancelled) {
      _cancelToken.cancel();
    }
    _cancelToken = new CancelToken();
    //答题数据
    ResponseInfo statisRresponseInfo = await DioUtils.instance.postRequest(
      url: HttpHelper.integralStatisticsRecoder,
      jsonMap: monthMap,
      cancelTag: _cancelToken,
    );

    if (statisRresponseInfo.success) {
      var responseData = statisRresponseInfo.data;
      if (responseData != null) {
        List list = responseData['list'];
        List<IntegralStatBean> newList = [];
        for (int i = 0; i < list.length; i++) {
          IntegralStatBean _rankStatBean = IntegralStatBean.fromJson(list[i]);
          newList.add(_rankStatBean);
        }
        _integralList = newList;

        if (responseData['userIntegral'] != null) {
          _userIntegralStatBean =
              IntegralStatBean.fromJson(responseData['userIntegral']);
        } else {
          _userIntegralStatBean = null;
        }
      }
    }
    _isLoading2 = false;
    _isLoading = false;

    if (mounted) {
      setState(() {});
    }

    return Future.value(true);
  }
}
